<template>
  <PageWrapper>
    <div :class="{ 'textSelect': textDisable}" :style="winWidth">
      <div style="display: inline-block;vertical-align: top;" :style = "leftClass">
        <Card class="!my-4 enter-y" :loading="loading" :style="cardHeight" style="overflow-y: scroll">
            <ElTree  class="fixTree" ref="treeRef" :data="treeData" node-key="childNodeCode" :default-expanded-keys="expandNodes" :props="defaultProps" @node-click="handleNodeClick" highlight-current>
              <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span><img src="../../../assets/images/dianzu.png" width="20" height="28"/>{{ node.label }}</span>
              </span>
              </template>
            </ElTree>
          <Loading :loading="treeLoading" absolute="true" :tip="loadingText"/>
        </Card>
      </div>
      <div class="draggable" style="width: 5px; display: inline-block;vertical-align: top;" :style="cardHeight"></div>
      <div style="display: inline-block;vertical-align: top;" :style = "rightClass">
        <Card class="!my-4 enter-y" :loading="loading" :style="cardHeight">
          <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick">
            <el-tab-pane label="优选物料" name="1">
              <el-form :inline="true" :model="formInline" class="demo-form-inline">
                <el-form-item label="搜索条件">
                </el-form-item>
                <el-form-item label="物料编码">
                  <el-input v-model="formInline.code" clearable style="width: 200px"/>
                </el-form-item>
                <el-form-item label="物料名称">
                  <el-input v-model="formInline.name" clearable style="width: 200px"/>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="onSubmit">搜索</el-button>
                </el-form-item>
              </el-form>
              <OfferingMaterialList ref="goodMaterial"/>
            </el-tab-pane>
            <el-tab-pane label="常规物料" name="2">
              <el-form :inline="true" :model="formInlineSecond" class="demo-form-inline">
                <el-form-item label="搜索条件">
                </el-form-item>
                <el-form-item label="物料编码">
                  <el-input v-model="formInlineSecond.code" clearable style="width: 200px"/>
                </el-form-item>
                <el-form-item label="物料名称">
                  <el-input v-model="formInlineSecond.name" clearable style="width: 200px"/>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="onSubmit">搜索</el-button>
                </el-form-item>
              </el-form>
              <OfferingMaterialList ref="commonMaterial"/>
            </el-tab-pane>

          </el-tabs>
          <div style="display: flex;height: 10px;align-items: center;margin-top: 20px" >
            <div style="background-color: #00bb00;width: 5px;height: 5px"></div>
            <div style="margin-left: 10px">支持按物料分类、物料编码、物料名称进行器件检索；</div>
          </div>
          <div style="display: flex;height: 10px;align-items: center;margin-top: 20px" >
            <div style="background-color: #00bb00;width: 5px;height: 5px"></div>
            <div style="margin-left: 10px">可显示器件的优选信息、以及对应品牌的物料信息；</div>
          </div>
        </Card>
      </div>
    </div>
  </PageWrapper>
</template>
<script lang="ts" setup>
import {computed, nextTick, ref} from 'vue';
  import { Card } from 'ant-design-vue';
  import { PageWrapper } from '/@/components/Page';
  import { defineComponent } from 'vue';
  import { BasicTree } from '/@/components/Tree';
  import { TreeItem } from '/@/components/Tree/index';
  import OfferingMaterialList from "@/views/PBI/material/component/OfferingMaterialList.vue";
  import { Loading } from '/@/components/Loading';

const treeLoading = ref(false);
const loadingText = ref('数据正在加载中...');
const expandNodes = ref([]);

interface Tree {
  parentNodeCode: string;
  parentNodeName: string;
  parentNodeType: string;
  childNodeCode: string;
  childNodeName: string;
  level: number;
  children?: Tree[];
}
  const winWidth = computed(() => {
    let winWidth = window.innerWidth-30;
    let winHeight = window.innerHeight - 70;
    return {
      width: winWidth + 'px',
      height: winHeight + 'px',
    };
  });

  const cardHeight = computed(() => {
    let winHeight = window.innerHeight - 70;
    return {
      height: winHeight + 'px',
    };
  });

  const defaultProps = {
    children: 'children',
    label: 'childNodeName',
  };

  const activeName = ref<String>('1');

  import { reactive } from 'vue'
import {TabsPaneContext} from "element-plus";
import * as API from "@/api/pbi/material";
import {useGlobSetting} from "@/hooks/setting";

  const formInline = ref({
    code: '',
    name: '',
  })

  const formInlineSecond = ref({
    code: '',
    name: '',
  })

  const onSubmit = () => {
    if (activeName.value === "1") {
      goodMaterial.value.filter(formInline.value);
    } else if (activeName.value === "2") {
      commonMaterial.value.filter(formInlineSecond.value);
    }
    console.log('submit!');
  }

  const nodeCode = ref<String>();
  const goodMaterial= ref()
  const commonMaterial= ref()
  const handleClick = (tab: TabsPaneContext, event: Event) => {
    console.log(tab.paneName)
    switch (tab.paneName) {
      case "1":
        formInline.value.code = '';
        formInline.value.name= '';
        goodMaterial.value.findTableData(nodeCode.value, 1);
        break;
      case "2":
        formInlineSecond.value.code = '';
        formInlineSecond.value.name= '';
        commonMaterial.value.findTableData(nodeCode.value, 0);
        break;
      default:
        break;
    }
    console.log(tab, event)
  }
  const loading = ref(false);

  const treeData =ref([]);


const handleNodeClick = async (data: Tree) => {
  //清除节点数据
  goodMaterial.value.tableData = [];
  goodMaterial.value.searchData = [];
  commonMaterial.value.tableData = [];
  commonMaterial.value.searchData = [];
  activeName.value = '1'
  formInline.value.code = '';
  formInline.value.name= '';
  if (data.children == null || data.children.length == 0) {
    nodeCode.value = data.childNodeCode;
    //调用第一个子组件的方法
    console.log("你点击了销售目录的节点");
    // 加载数据
    goodMaterial.value.findTableData(nodeCode.value, 1);
  }
  // nextTick(()=>{
  //   addWatch();
  // })
  console.log(data);
};

// 递归函数
const dg = function(list, res) {
  list.forEach(item=> {
    const itemCh = res.filter(a => a.childNodeCode != '' && a.childNodeCode != null && a.parentNodeCode == item.childNodeCode)
    if (itemCh && itemCh.length >0) {
      itemCh.sort((a,b) => a.childNodeName.localeCompare(b.childNodeName))
      item.children = itemCh;
      // 再次调用dg这个函数 再走一遍
      dg(item.children, res);
    }
  })
}

const initTree = async () => {
  treeLoading.value = true
  try {
    const {materialRootId} = useGlobSetting();
    const res = await API.getClassificationTree({rootNode: materialRootId});
    if (res) {
      console.log(res);
      const level1List = res.filter(a => a.level == '1')
      if (level1List && level1List.length > 0) {
        // 排序
        level1List.sort((a,b) => a.childNodeName.localeCompare(b.childNodeName))
        dg(level1List, res);
        //构造根对象
        const rootNode = {
          "parentNodeCode": "",
          "parentNodeName": "",
          "parentNodeType": "",
          "childNodeCode": level1List[0].parentNodeCode,
          "childNodeName": level1List[0].parentNodeName,
          "level": 0,
          "children": level1List
        }
        console.log(rootNode)
        treeData.value.push(rootNode)
        expandNodes.value.push(rootNode.childNodeCode)

        nextTick(()=>{
          addWatch();
        })
      }
      console.log('dwfw7777777777777777777')
      console.log(treeData.value)
    }
  } finally {
    treeLoading.value = false
  }

}

const textDisable = ref<boolean>(false)
const leftWidth = ref<number>((window.innerWidth -30) *0.15 )
const rightWidth = ref<number>()
const leftClass = computed(() => {
  return {
    width: leftWidth.value + 'px',
  };
});
const rightClass = computed(() => {
  let winWidth = window.innerWidth-30 -leftWidth.value-5;
  return {
    width: winWidth + 'px',
  };
});
nextTick(()=> {
  let draggable = document.querySelector('.draggable');
  draggable.onmousedown = function (e) {
    let startX = e.clientX;
    let startLeft = leftWidth.value;
    textDisable.value = true
    document.onmousemove = function (e) {
      // 在这里处理拖动事件
      let offset = e.clientX - startX
      if (startLeft + offset > (window.innerWidth - 30) * 0.3) {
        leftWidth.value = (window.innerWidth - 30) * 0.3
      } else if (startLeft + offset < (window.innerWidth - 30) * 0.15) {
        leftWidth.value = (window.innerWidth - 30) * 0.15
      } else {
        leftWidth.value = startLeft + offset;
      }
    }
    document.onmouseup = function (ev) {
      ev.stopPropagation()
      document.onmousemove = null;
      document.onmouseup = null
      textDisable.value = false
    };
  };
  // document.querySelector('.draggable').addEventListener('mousedown', function(e) {
  //   let startX = e.clientX;
  //   // let startWidth = parseFloat(getComputedStyle(this).width);
  //   console.log("点击拖拽")
  //   document.documentElement.addEventListener('mousemove', resize);
  //   document.documentElement.addEventListener('mouseup', stopResize);
  //   // document.querySelector('.draggable').addEventListener('mouseout', function (e) {
  //   //   document.documentElement.removeEventListener('mousemove',resize);
  //   // });
  //   function resize(e) {
  //       // 在这里处理拖动事件
  //       let offset = e.clientX - startX
  //       if (leftWidth.value + offset > (window.innerWidth - 30) * 0.3) {
  //         leftWidth.value =  (window.innerWidth - 30) * 0.3
  //       } else if (leftWidth.value + offset < 200) {
  //         leftWidth.value = 200
  //       } else {
  //         leftWidth.value = leftWidth.value + offset;
  //       }
  //     }
  //
  //   function stopResize() {
  //     document.documentElement.removeEventListener('mousemove',resize);
  //     document.documentElement.removeEventListener('mouseup', stopResize);
  //   }
  // });

})
initTree();
const treeRef = ref(null);
const addWatch = ()=>{
  let elTree = treeRef.value.$el
  if (elTree != null) {
    let elNode = elTree.firstElementChild;
    if (elNode != null && elNode.className === 'el-tree-node is-expanded is-focusable') {
      // debugger
      let val = treeRef.value.$el.firstElementChild.clientWidth
      leftWidth.value =  val + 60 - 3;
      // debugger
      console.log("宽度已变化");
      // watch(()=>{
      //   return parentRef.value.$el.firstElementChild.clientWidth;
      // },(value)=>{
      //   console.log("宽度已变化2");
      //   debugger
      //   leftWidth.value = (value + 60);
      //   console.log(leftWidth.value);
      // },{immediate: true})
      // watchEffect(() => {
      //   // 获取子元素的宽度
      //   if (parentRef.value.$el.firstElementChild) {
      //     console.log(parentRef.value.$el.firstElementChild)
      // debugger
      // console.log(parentRef.value.el$)
      // const childWidth = parentRef.value.clientWidth;
      // leftWidth.value = parentRef.value.$el.firstElementChild.clientWidth;
      // console.log('子元素的宽度：', childWidth);
      //   }
      // });
    }
  }

}
</script>
<style scoped>
  /*.fixTree{*/
  /*  display:inline-block;*/
  /*}*/
  .el-tree > :nth-child(n+1) {
    display: inline-block;
    min-width: 100%;
  }

  :deep(.el-tree>.el-tree-node) {
    min-width:100%;
    display: inline-block;
  }

  .draggable {
    margin-top: 18px;
    width: 5px; /* 设置竖线的宽度 */
    /*height: 100%; !* 设置竖线的高度 *!*/
    background-color: #ffffff; /* 设置竖线的颜色 */
    /*position: absolute;*/
    /*top: 0;*/
    /*left: 50%; !* 设置竖线在页面中的位置 *!*/
    /*transform: translateX(-50%); !* 将竖线居中对齐 *!*/
    z-index: 999; /* 确保竖线位于其他元素之上 */
    /*cursor: ew-resize;*/
    /*resize: horizontal;*/
    cursor: col-resize;
  }
  .draggable:hover{
    /* 设置光标样式为左右调整大小 */
    /*cursor: ew-resize;*/
    background-color: #595454;
  }
  .draggable:active{
    /* 设置光标样式为左右调整大小 */
    /*cursor: ew-resize;*/
    background-color: #595454;
  }
  /* 禁用文本选择 */
  .textSelect {
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
  }

</style>
